package cn.keyingbo.nettylearning.message.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.EventExecutorGroup;
import org.apache.log4j.Logger;

/**
 * 服务器消息处理器
 */
public class MessageServerHandler extends ChannelInboundHandlerAdapter {
    private static Logger log = Logger.getLogger(MessageServerHandler.class.getClass());
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("server channel active... ");
    }

    /**
     * 读取传进来的信息并处理
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String body = (String) msg;
        log.info("Server received: " + body );
        ByteBuf resp = Unpooled.copiedBuffer((body + System.getProperty("line.separator")).getBytes());
        //通过ChannelHandlerContext的write方法异步发送应答消息给客户端
        if ("bye".equals(body)){//如果传过来bye标志位，则关闭连接
            ctx.writeAndFlush(resp)
                .addListener(ChannelFutureListener.CLOSE);
        } else {
            ctx.writeAndFlush(resp);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error(cause.getMessage(),cause);
        ctx.close();
    }
}
